# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, render_to_response
from django.core.urlresolvers import reverse
#from loader import DataLoader
from pao.models import Temporal, Repemp
from forms import UploadFileForm, ModificarRFC
from loader import XlsxLoader
from django.views.decorators.csrf import csrf_protect
from django.core.context_processors import csrf 
from django.core.files.uploadedfile import UploadedFile
from django.db.models import Count

#@csrf_protect
def upload(request):
    #c={}
    #c.update(csrf(request))
    if request.method =='POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #try:
                fl = request.FILES['filename'] 
                a =XlsxLoader(fl)
                a.extract()
                return HttpResponseRedirect('/listado')
            #except:
            #    return render_to_response('upload_error.html')
            
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form':form})
    #return render_to_response("error.html",{'r':request})
    
def uploadSuccess(request):
    return render_to_response('upload_success.html')
def uploadError(request):
    return render_to_response('upload_error.html')
def index(request):
    return render_to_response('index.html')
def faltantes():
    
    u = Temporal.objects.latest('latest_add')
    t = Temporal.objects.filter(latest_add=u.latest_add, estatus=1).order_by('id')
    tabla=[]
    registro={}
    tt=0
    for o in t:
        try:
            p = Repemp.objects.get(pk = o.rfc)
        except Repemp.DoesNotExist:
            idt = o.id+1
            registro = {'rfc':o.rfc,'nombre':o.nombre, 'id':idt}
            tabla.insert(tt,registro)
            tt+=1
    return tabla
def objetos():
    
    u = Temporal.objects.latest('latest_add')
    t = Temporal.objects.filter(latest_add=u.latest_add, estatus=1)
    tabla=[]
    registro ={}
    for o in t:
        try:
            r = Repemp.objects.get(pk=o.rfc)
            registro={'rfc':r.rfc,'nombre':r.nombre}
            tabla.append(registro)
        except Repemp.DoesNotExist:
            pass
    return tabla
def listado(request):
   
    
    if faltantes:
        a = faltantes()
    b = objetos()
    
    return render_to_response('listado.html',{'faltantes':a, 'completados':b})
def modificar(request, rfc):
    if request.method =='POST':
        forma = ModificarRFC(request.POST)
        if forma.is_valid():
            #todo
            old_rfc = 0
            new_rfc = 0
            return HttpResponseRedirect('/test.page.html',{'old_rfc':old_rfc, 'new_rfc':new_rfc})
    else:
        forma = ModificarRFC()
    return render_to_response("modificar.html", {'form':forma, 'rfc':rfc})
def actualizar(request, rfc):
    obj = get_object_or_404(Temporal, pk=rfc)
    try:
        older = rfc
        newer = request.POST['new_rfc']
        p=Temporal.objects.filter(pk=rfc).update(rfc=newer)        
        #p.save()
        #a=Temporal.objects.get(pk=request.POST['old_rfc'])
        #a.rfc = request.POST['new_rfc']
    except (KeyError):
        return render_to_response('/listado')
            
    #return render_to_response('test.page.html',{'older':older, 'newer':newer})
    return HttpResponseRedirect('/listado')
def ignorar(request, rfc):
    
    obj = get_object_or_404(Temporal, pk=rfc)
    try:
        p = Temporal.objects.filter(pk=rfc).update(estatus=0)
    except (KeyError):
        return render_to_response('/listado')
            
    return HttpResponseRedirect('/listado')
def consultar(request):
    suma=0
    try:
        p = Temporal.objects.values('file_name','latest_add','hashid').annotate(total=Count('id')).order_by('-latest_add')
        s = Temporal.objects.values('estatus').annotate(tglobal=Count('id'))
        ta = s[0]['tglobal']
        ti = s[1]['tglobal']
        return render_to_response('consultar.html',{'datos':p,'total_activos':ta, 'total_inactivos':ti})
    except Temporal.DoesNotExist:
        pass
    return render_to_response('/listado')
def grupo(self, hash_id):
    try:
        todos = Temporal.objects.filter(estatus=1).filter(hashid=hash_id).order_by('id')
    except Temporal.DoesNotExist:
        pass
    return render_to_response("grupo.html",{'datos':todos})